package com.dangz.dans.runner;

import com.corundumstudio.socketio.BroadcastOperations;
import com.corundumstudio.socketio.SocketIOClient;
import com.corundumstudio.socketio.SocketIOServer;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.CommandLineRunner;
import org.springframework.stereotype.Component;
import java.util.Collection;

/**
 * @author dangz
 * @since 2018/6/25 16:13
 */
//@Component
public class NettyServerRunner implements CommandLineRunner {
    private final SocketIOServer server;

    @Autowired
    public NettyServerRunner(SocketIOServer server) {
        this.server = server;
    }

    @Override
    public void run(String... args) throws Exception {
        server.start();
        System.out.println("netty-socketIO启动……");
    }

    /*
     * 全体消息推送
     * @param type 前台根据类型接收消息，所以接收的消息类型不同，收到的通知就不同
     * 推送的事件类型
     * @param content
     * 推送的内容
     */
    public void pushArr(String type, String content) {
        //获取全部客户端
        Collection<SocketIOClient> allClients = server.getAllClients();
        for (SocketIOClient socket : allClients) {
            //给所有客户端发送消息
            socket.sendEvent(type, content);
        }
    }

    /*
     * 指定房间的全体消息推送
     * @param type 前台根据类型接收消息，所以接收的消息类型不同，收到的通知就不同
     * 推送的事件类型
     * @param room
     * 房间标识
     * @param content
     * 推送的内容
     */
    public void pushArr(String type, String room, String content) {
        //获取指定房间的全部客户端
        BroadcastOperations operations = server.getRoomOperations(room);
        operations.sendEvent(type, content);
    }
}
